package io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Main {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 8080));
        serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8080));

        SocketChannel channel = serverSocketChannel.accept();
        channel.configureBlocking(false);


        Selector selector = Selector.open();
        SelectionKey registerKey = channel.register(selector, SelectionKey.OP_READ);
        System.out.println(registerKey);


        while (true) {
            System.out.println(System.currentTimeMillis());

            int readyChannels = selector.select();
            if (readyChannels == 0) {
                continue;
            }


            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    System.out.println("a connection was accepted by a ServerSocketChannel.");
                }
                if (key.isConnectable()) {
                    System.out.println("a connection was established with a remote server.");
                }
                if (key.isReadable()) {
                    System.out.println("a channel is ready for reading");
                }
                if (key.isWritable()) {
                    System.out.println("a channel is ready for writing");
                }
                // 处理完删除
                keyIterator.remove();
            }
        }
    }


}
